package com.shakespace.artofandroid.chapter03.conflict

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup

@Suppress("UNUSED_VARIABLE")
class ConflictDemoView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    ViewGroup(context, attrs, defStyleAttr) {

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {


    }

    /** --------------------METHOD TWO , do on child's dispatchTouchEvent--------------*/
    /**
     * in thie method , Parent also need do intercept ,  return true in onInterceptTouchEvent except Event.DOWN
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        var eventX = ev.x
        var eventY = ev.y

        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                requestDisallowInterceptTouchEvent(true)
            }

            MotionEvent.ACTION_MOVE -> {
                // if parent need handle
                requestDisallowInterceptTouchEvent(false)
            }

            MotionEvent.ACTION_UP -> {
            }
            else -> {
            }
        }
        return super.dispatchTouchEvent(ev)
    }


    /** --------------------METHOD ONE , do on parent's onInterceptTouchEvent--------------*/
    var flag = true
    var lastX: Float = 0f
    var lastY: Float = 0f

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {

        var intercepted = false

        var eventX = ev.x
        var eventY = ev.y

        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                // parent should return false , or child can't receive the event
                intercepted = false
            }

            MotionEvent.ACTION_MOVE -> {
                // depends on your logic , if need parent work , return true
                intercepted = flag
            }

            MotionEvent.ACTION_UP -> {
                // return false , then child can handle Event UP
                intercepted = false
            }
            else -> {
            }
        }

        lastX = eventX
        lastY = eventY

        return intercepted
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return super.onTouchEvent(event)
    }

    private val touchListener = object : View.OnTouchListener {
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }
    }
}